import {makeAutoObservable, runInAction} from "mobx";
import axios from "axios";

axios.interceptors.request.use(config => {
    
    return config;
},error => {
    return Promise.reject(error);
});

axios.interceptors.response.use(response => {
    
    return response;
},error => {
    return Promise.reject(error);
});

class BookStore {
    books = [];
    about = [];
    isLoading = false;
    error = null;

    constructor() {
        makeAutoObservable(this);
    }

    fetchBooks = async () => {
        this.isLoading = true;
        try {
            const booksRes = await axios.get('http://localhost:3004/books')
            runInAction(() => {
                this.books = booksRes.data;
                this.error = null;
            });
            console.log(booksRes.data);
        }catch (error) {
            this.error = error;
            return Promise.reject(error);
        }finally {
            runInAction(() => {
                this.isLoading = false;
            })
        }
    }
    fetchBooksById = async (Id) => {
        this.isLoading = true;
        try {
            const aboutRes = await axios.get(`http://localhost:3004/about?id=${Id}`)
                
            runInAction(() => {
                this.about = aboutRes.data[0];
                this.error = null;
            });
            console.log(aboutRes.data);
        }catch (error) {
            this.error = error;
            return Promise.reject(error);
        }finally {
            runInAction(() => {
                this.isLoading = false;
            })
        }
    }
}

export default new BookStore();